
// 发布文章
function postArticle() {
    var userId = $('#userId').val();
    var articleCategory = $('#articleCategory').val();
    var title = $('#title').val();
    var content = $('#content').val();
    // var picture = $('#articlePhoto').val();
    var json = {
        userId: userId,
        sortId: articleCategory,
        articleTitle: title,
        articleContent: content
    };
    if(content == undefined || content == ""){
        toastr.warning("文章内容不能为空");
        return;
    }
    if(title == undefined || title == ""){
        toastr.warning("文章标题不能为空");
        return;
    }
    $.ajax({
        type:"POST",
        url:"http://localhost:8081/article/save",
        data:JSON.stringify(json),
        dataType:"json",
        contentType:"application/json",
        success:function (result) {
            // 刷新页面
            toastr.success(result.message);
            setTimeout(function() {
                window.location.reload();
            }, 2000)
        }, error: function() {
            location.reload();
        }
    });
}

// 更新文章
function update(ele) {
    var id =$(ele).attr("article-id");
    $('#updateBtn').attr("articleId", id);
    $.ajax({
        type: "get",
        url: "http://localhost:8081/admin/article/" + id,
        dataType: "json",
        async: false,
        success: function (json) {
            $('#articleTitles').val(json.articleTitle);
            $('#articleSummary').val(json.articleSummary);

            // 填充分类数据
            $.ajax({
                url: "http://localhost:8081/category/list",
                type: "GET",
                dataType: "json",
                async: false,
                success: function (json) {
                    $('#updateCategories').html("");
                    $.each(json, function (i, item) {
                        $('#updateCategories').append('<option categoryId="' + item.id + '">' + item.name + '</option>');
                    });
                }
            });
            var select = document.getElementById("updateCategories");
            for (var i = 0; i < select.options.length; i++) {
                if (select.options[i].innerHTML === json.sort.sortName) {
                    select.options[i].selected = true;
                    break;
                }
            }
            $('#articleContents').val(json.articleContent);
        }
    });
    // 显示模态框
    $('#updateModal').modal();
}
